package cn.yangke.org.service.impl;

import cn.yangke.basic.service.impl.BaseServiceImpl;
import cn.yangke.basic.util.MD5Utils;
import cn.yangke.basic.util.StrUtils;
import cn.yangke.org.domain.Employee;
import cn.yangke.org.mapper.EmployeeMapper;
import cn.yangke.org.service.IEmployeeService;
import cn.yangke.user.domain.Logininfo;
import cn.yangke.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author YangKe
 * @Date 2022/6/1 18:24
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void save(Employee employee) {
        initEmployee(employee);
        //写一个方法复制相关的字段
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);
        //设置logininfo_id
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
    }

    /**
     * 加密密码
     * @param employee
     */
    private void initEmployee(Employee employee) {
        //获取32位盐值加密
        String salt = StrUtils.getComplexRandomString(32);
        //加密密码
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        //保存盐值加密
        employee.setSalt(salt);
        //保存加密后的密码
        employee.setPassword(md5Pwd);
    }

    /**
     *
     * @param employee
     * @return
     */
    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        //设置type类型
        logininfo.setType(0);
        return logininfo;
    }
}
